package com.htfyun.fragment.read;

import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.htfyun.Constants;
import com.htfyun.ScanMyBooksDirManager;
import com.htfyun.utils.DebugLog;
import com.htfyun.utils.DisplayUtil;
import com.htfyun.view.EmptyRecyclerView;
import com.htfyun.view.GridSpacingItemDecoration;

import org.geometerplus.android.fbreader.covers.CoverManager;
import org.geometerplus.android.fbreader.libraryService.BookCollectionShadow;
import org.geometerplus.android.fbreader.util.AndroidImageSynchronizer;
import org.geometerplus.fbreader.Paths;
import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.book.BookEvent;
import org.geometerplus.fbreader.book.IBookCollection;
import org.geometerplus.fbreader.formats.PluginCollection;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.filetypes.FileType;
import org.geometerplus.zlibrary.core.filetypes.FileTypeCollection;
import org.geometerplus.zlibrary.ui.android.R;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by sst on 2017/11/21.
 */
public class ReadFragment_bk extends SupportFragment {

    private EmptyRecyclerView mRecy;
    
    private ReadAdapter readAdapter;

    private ImageView imgReadingBook;
    private TextView txtPagePercent;
    private TextView txtDate;
    private TextView txtBookTitle;
    private TextView txtBookAuthor;
    private ProgressBar progressBarPagePercent;
    
    
    private ImageView imgNext;
    private ImageView imgPrevious;
    private TextView txtPercent;

    private final BookCollectionShadow myCollection = new BookCollectionShadow();

    public static final String MYBOOKS_PATH = Environment.getExternalStorageDirectory().toString() + "/myBook/";

    private AndroidImageSynchronizer ImageSynchronizer;
    private CoverManager myCoverManager;

    public static ReadFragment_bk newInstance() {

        Bundle args = new Bundle();

        ReadFragment_bk fragment = new ReadFragment_bk();
        fragment.setArguments(args);

     
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.htfyun_read_fragment, container, false);

        ImageSynchronizer = new AndroidImageSynchronizer(_mActivity);

        final int coverHeight = DisplayUtil.dipToPix(_mActivity, Constants.COVER_HEIGHT);
        final int coverWidth = DisplayUtil.dipToPix(_mActivity, Constants.COVER_WIDTH);

        myCoverManager = new CoverManager(_mActivity, ImageSynchronizer, coverWidth /*15 / 32*/, coverHeight);

        initView(view);
        return view;
    }

    private void initView(View view) {

        imgReadingBook = (ImageView) view.findViewById(R.id.imgReadingBook);
        txtPagePercent = (TextView) view.findViewById(R.id.txtPagePercent);
        txtDate = (TextView) view.findViewById(R.id.txtDate);
//        txtDate.setVisibility(View.INVISIBLE);
        txtBookTitle = (TextView) view.findViewById(R.id.txtBookTitle);
        txtBookAuthor = (TextView) view.findViewById(R.id.txtBookAuthor);
        progressBarPagePercent = (ProgressBar) view.findViewById(R.id.progressBarPagePercent); 

        imgNext = (ImageView) view.findViewById(R.id.imgNext);
        imgPrevious = (ImageView) view.findViewById(R.id.imgPrevious);
        txtPercent = (TextView) view.findViewById(R.id.txtPercent);
        
        mRecy = (EmptyRecyclerView) view.findViewById(R.id.recyclerView);

        View emptyView = view.findViewById(R.id.emptyView);
        mRecy.setEmptyView(emptyView);
        mRecy.setNestedScrollingEnabled(false);

//        final GridLayoutManager manager = new GridLayoutManager(_mActivity, 4, LinearLayoutManager.HORIZONTAL, false);
        final GridLayoutManager manager = new GridLayoutManager(_mActivity, 4);
        
        mRecy.setLayoutManager(manager);

        int space = getContext().getResources().getDimensionPixelSize(R.dimen.read_added_books_space);
        mRecy.addItemDecoration(new GridSpacingItemDecoration(4, space, true));

        readAdapter = new ReadAdapter(_mActivity);
        mRecy.setAdapter(readAdapter);

        initRecentReadingBook();
        connectionBindToService();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        
        myCollection.unbind();
    }

    private void initRecentReadingBook() {

            myCollection.bindToService(getContext(), new Runnable() {
                public void run() {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            Book book = myCollection.getRecentBook(0);

                            if (book != null) {

                                if (!myCoverManager.trySetCoverImage(imgReadingBook, book, PluginCollection.Instance(Paths.systemInfo(_mActivity)))) {

                                    final FileType fileType = FileTypeCollection.Instance.typeForFile(ZLFile.createFileByPath(book.getPath()));
                                    DebugLog.e("fileTyp.id = " + fileType.Id);
                                    imgReadingBook.setImageResource(R.drawable.ic_shelf_txt);
                                    imgReadingBook.setBackgroundResource(R.drawable.shape_rect_bg);
                                }

                                txtBookAuthor.setText(book.authorsName());
                                txtBookTitle.setText(book.getTitle());
                                if (book.getProgress() != null) {
                                    txtPagePercent.setText(book.getProgress().Numerator + "/" + book.getProgress().Denominator);
                                    progressBarPagePercent.setMax((int)book.getProgress().Denominator);
                                    progressBarPagePercent.setProgress((int)book.getProgress().Numerator);
                                }


                                File file = new File(book.getPath());
                                long time = file.lastModified();
                                txtDate.setText(getDateTimeFromMillisecond(time));
                                
                            }
                            
                        }
                    });
                }
            });
        
    }
    
    
    private int getSpanCount() {
        RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();
//        判断是当前layoutManager是否为LinearLayoutManager
//        只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;

            return manager.getSpanCount() * 2;

        }

        return 8;
    }

    private int getTotalPages() {
        RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();
//        判断是当前layoutManager是否为LinearLayoutManager
//        只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
        if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;

            int span = getSpanCount();

            int pages = readAdapter.getItemCount() / span;
            if (readAdapter.getItemCount() % span != 0) {
                pages += 1;
            }

            return pages;

        }

        return 1;
    }
    
    private void setTextLibraryItemPageByPosition(int position) {

        final int page = position / getSpanCount() + 1;
        txtPercent.setText(getString(R.string.reading_recently_added_pages, page, getTotalPages()));

    }

    private void addedBooksForPages(final int totalBooks) {
        float page = 1.0f * totalBooks / (getSpanCount());
        
        if (page <= 1) {
            imgNext.setVisibility(View.INVISIBLE);
            imgPrevious.setVisibility(View.INVISIBLE);
            txtPercent.setVisibility(View.INVISIBLE);
            return;
        }

        imgNext.setVisibility(View.VISIBLE);
        imgPrevious.setVisibility(View.VISIBLE);
        txtPercent.setVisibility(View.VISIBLE);

        setTextLibraryItemPageByPosition(0);
        
        imgPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();

                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = linearManager.findLastCompletelyVisibleItemPosition();
                    //获取第一个可见view的位置
                    int firstItemPosition = linearManager.findFirstCompletelyVisibleItemPosition();

                    DebugLog.e("previous -> lastItemPosition = " + lastItemPosition + ", firstItemPosition = " + firstItemPosition);
                    
                    if (firstItemPosition == 0) {
                        setTextLibraryItemPageByPosition(firstItemPosition);
                        return;
                    }   

                    final int showItemCount = lastItemPosition - firstItemPosition;
                    int newPosition = firstItemPosition - showItemCount;// + 1;

                    if (newPosition < 0) {
                        newPosition = 0;
                    }

                    setTextLibraryItemPageByPosition(newPosition);

                    linearManager.scrollToPosition(newPosition);
                }

            }
        });

        imgNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                RecyclerView.LayoutManager layoutManager = mRecy.getLayoutManager();

                //判断是当前layoutManager是否为LinearLayoutManager
                // 只有LinearLayoutManager才有查找第一个和最后一个可见view位置的方法
                if (layoutManager instanceof GridLayoutManager) {
                    GridLayoutManager manager = (GridLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = manager.findLastCompletelyVisibleItemPosition();
                    //获取第一个可见view的位置
                    int firstItemPosition = manager.findFirstCompletelyVisibleItemPosition();

                    DebugLog.e("next -> lastItemPosition = " + lastItemPosition + ", firstItemPosition = " + firstItemPosition);

                    if (lastItemPosition == readAdapter.getItemCount() - 1) {
                        setTextLibraryItemPageByPosition(lastItemPosition);
                        return;
                    }

                    final int showItemCount = lastItemPosition - firstItemPosition;
                    int newPosition = lastItemPosition + showItemCount;// - 1;

                    if (newPosition > readAdapter.getItemCount() - 1) {

                        newPosition = readAdapter.getItemCount() - 1;
                    }

                    setTextLibraryItemPageByPosition(newPosition);

                    manager.scrollToPosition(newPosition);
                }


            }
        });



    }
    
    private void connectionBindToService() {
        myCollection.bindToService(getContext(), new Runnable() {
            public void run() {
                myCollection.addListener(bookListener);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        List<File> booksPath = getAddedBooks();
                        List<Book> addedBooks = new ArrayList<>();

                        for (File bookFile : booksPath) {
                            if (!bookFile.exists() || bookFile.isDirectory()) {
                                continue;
                            }


                            try {
                                long time = bookFile.lastModified();
                                String date = getDateTimeFromMillisecond(time);
                                DebugLog.e("date = " + date);

                            } catch (Exception e) {
                                DebugLog.e("error to get lastModified time");
                            }

                            Book myBook = myCollection.getBookByFile(bookFile.getPath());
                            if (myBook != null) {
                                addedBooks.add(myBook);
                            }
                        }

                        readAdapter.setDatas(addedBooks);
                        readAdapter.notifyDataSetChanged();

                        addedBooksForPages(addedBooks.size());

                    }
                });
            }
        });
    }


    IBookCollection.Listener<Book> bookListener = new IBookCollection.Listener<Book>() {
        @Override
        public void onBookEvent(BookEvent event, Book book) {

//            myCollection.bindToService(getContext(), new Runnable() {
//                public void run() {
//                    myCollection.addListener(bookListener);
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            List<Book> recentBooks = myCollection.recentlyOpenedBooks(6);
//                            readAdapter.setDatas(recentBooks);
//                            readAdapter.notifyDataSetChanged();
//                        }
//                    });
//                }
//            });
            
        }

        @Override
        public void onBuildEvent(IBookCollection.Status status) {

        }
    };

    public static String getDateTimeFromMillisecond(long millisecond){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(millisecond);
        String dateStr = simpleDateFormat.format(date);
        return dateStr;
    }
    
    private static final String SUFFIX_TXT = "txt";
    private static final String SUFFIX_PDF = "pdf";
    private static final String SUFFIX_EPUB = "epub";

    private List<File> getAddedBooks() {

        return ScanMyBooksDirManager.INSTANCE.getFiles();

//        
//        List<String> paths = new ArrayList<>();
//
//        File file = new File(MYBOOKS_PATH);
//        if (file.isDirectory()) {
//            File[] books = file.listFiles();
//            for (File book : books) {
//                if (book.isFile()) {
//
//                    try {
//                        long time = book.lastModified();
//                        String date = getDateTimeFromMillisecond(time);
//                        DebugLog.e("date = " + date);
//
//                    } catch (Exception e) {
//                        DebugLog.e("error to get lastModified time");
//                    }
//                    
//                    
//
//                    String bookName = book.getName();
//                    final int index = bookName.lastIndexOf('.');
//
//                    String myExtension = (index > 0) ? bookName.substring(index + 1).toLowerCase().intern() : "";
//
//                    if (myExtension == SUFFIX_TXT || myExtension == SUFFIX_PDF || myExtension == SUFFIX_EPUB) {
//                        paths.add(book.getPath());
//                    }
//                }
//                      
//            }
//            
//         
//
//            return paths;
//        }
//
//        return Collections.emptyList();
    }

}
